package com.lkm.asking.controller;

import com.lkm.asking.entity.*;
import com.lkm.asking.service.*;
import com.lkm.asking.util.AvaterUtil;
import com.lkm.asking.util.DefaultAvater;
import com.lkm.asking.util.MD5Util;
//import org.elasticsearch.client.ml.calendars.Calendar;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/user")
public class UserController {
    @Value("${IP}")
    String ip;

    Map<String, Object> modelMap = new HashMap<>();
    AvaterUtil avaterUtil = new AvaterUtil();
    DefaultAvater defaultAvater = new DefaultAvater();

    @Autowired
    UserService userService;

    @Autowired
    AnswerService answerService;

    @Autowired
    DataService dataService;

    @Autowired
    QuestionService questionService;

    @Autowired
    KeyService keyService;

    @Autowired
    DownFileService downFileService;

    @Autowired
    CounterService counterService;

//
//    private static final String KEY = "abc123"; // KEY为自定义秘钥
//
//
//    @RequestMapping(value = "/sendMsg", method = RequestMethod.POST, headers = "Accept=application/json")
//    public Map<String, Object> sendMsg(@RequestBody Map<String,Object> requestMap) {
//        String phoneNumber = requestMap.get("phoneNumber").toString();
//        String randomNum = CommonUtils.createRandomNum(6);// 生成随机数
//        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
//        Calendar c = Calendar.getInstance();
//        c.add(Calendar.MINUTE, 5);
//        String currentTime = sf.format(c.getTime());// 生成5分钟后时间，用户校验是否过期
//        sengMsg(); //此处执行发送短信验证码方法
//        String hash =  MD5Utils.getMD5Code(KEY + "@" + currentTime + "@" + randomNum);//生成MD5值
//        Map<String, Object> resultMap = new HashMap<>();
//        resultMap.put("hash", hash);
//        resultMap.put("tamp", currentTime);
//        return resultMap; //将hash值和tamp时间返回给前端
//    }
//
//    @RequestMapping(value = "/validateNum", method = RequestMethod.POST, headers = "Accept=application/json")
//    public Map<String, Object> validateNum(@RequestBody Map<String,Object> requestMap) {
//        String requestHash = requestMap.get("hash").toString();
//        String tamp = requestMap.get("tamp").toString();
//        String msgNum = requestMap.get("msgNum").toString();
//        String hash = MD5Util.MD5(KEY + "@" + tamp + "@" + msgNum);
////
//        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
//        Calendar c = Calendar.getInstance();
//        String currentTime = sf.format(c.getTime());
//
//
//        if (tamp.compareTo(currentTime) > 0) {
//            if (hash.equalsIgnoreCase(requestHash)){
//                //校验成功
//            }else {
//                //验证码不正确，校验失败
//            }
//        } else {
//            // 超时
//        }
//    }
//
//






    @ResponseBody
    @RequestMapping(value = "/register")
    public Map<String, Object> insertUser(@RequestBody Map<String, Object> data) {
        modelMap.clear();
        String username = (String) data.get("username");
        User user = new User();
        user.setNickname((String) data.get("nickname"));
        user.setUsername(username);
//        MD5Util.MD5加密做用
        String password = (String) data.get("password");
        if(password.length()<8){
            modelMap.put("msg","密码不能少于八位！");
            return modelMap;
        }
        user.setEmail((String) data.get("email"));
        user.setPassword(MD5Util.MD5(password));
//        user.setPassword((String) data.get("password"));
        File file = new File("D:/CODE/finally2/personal/files/asking/avaters/default.jpg");
        defaultAvater.avaterUpload(file,username);
        String url = ip + "/user/avaters/" + username + "/" + username + ".jpg";
        user.setAvater(url);
        User judge = userService.queryByUsername(user.getUsername());
        if (judge == null) {
            int flag = userService.insertUser(user);
            modelMap.put("errno", 0);
            modelMap.put("msg", "注册成功！");
        } else {
            modelMap.put("errno", 1);
            modelMap.put("msg", "用户名已被占用！");
        }
        return modelMap;
    }

    @ResponseBody
    @RequestMapping(value = "/updateavater")
    public Map<String, Object> updateAvater(@RequestParam("avater") MultipartFile file,
                                            @RequestParam("username") String username) {
        modelMap.clear();
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (suffix.equals(".jpg") || suffix.equals(".JPG")) {
            avaterUtil.avaterUpload(file, username);
            String webUrl = ip + "/user/avaters/" + username + "/" + username + suffix.toLowerCase();
            int flag = userService.updateAvater(username, webUrl);
            if (flag > 0) {
                modelMap.put("errno", 0);
                modelMap.put("url", webUrl);
            } else {
                modelMap.put("errno", -1);
                modelMap.put("msg", "头像更新失败！");
            }
        } else {
            modelMap.put("errno", 1);
            modelMap.put("msg", "请上传以.jpg结尾的图片文件");
        }
        return modelMap;

    }

    @ResponseBody
    @RequestMapping(value = "/login")
    public Map<String, Object> signin(@RequestBody Map<String, Object> data) {
        modelMap.clear();
        String username = (String) data.get("username");
         String password = MD5Util.MD5((String) data.get("password"));
//        String password = (String) data.get("password");
        System.out.println(username);
        System.out.println(password);
        Integer queCount = questionService.countQuestion(username);
        Integer ansCount = answerService.countAnswer(username);
        userService.updateInfo(queCount, ansCount, username);
        User con = userService.userLogin(username, password);
        if (con != null) {
            modelMap.put("errno", 0);
            modelMap.put("result", con);
        } else {
            modelMap.put("errno", -1);
            modelMap.put("msg", "用户名或密码错误");
        }
        return modelMap;
    }

    @ResponseBody
    @RequestMapping(value = "/sendkey")
    public Map<String ,Object> sure(@RequestBody Map<String,Object> data){
        modelMap.clear();
        String uname = (String) data.get("username");
        String key = String.format("%04d",new Random().nextInt(9999));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String umail=userService.getMail(uname);

        try{
            HtmlEmail email = new HtmlEmail();//创建一个实例对象
            email.setHostName("smtp.qq.com");//邮箱STMP服务器
            email.setCharset("utf-8");//设置发送的字符类型
            email.addTo(umail);//设置收送人的邮箱和用户名
            email.setFrom("2644819828@qq.com","asking");
            email.setAuthentication("2644819828@qq.com","zfmwtlrwykijebfh");//发送人邮箱和授权码
            email.setSubject("Asking欢迎您！");//发送主题
            email.setMsg("亲爱的asking用户【"+  uname +"】您好！欢迎您使用Asking，您的验证码是："+ key +". 请您保护好您的验证码！请勿告诉他人！");
            email.send();//发送

        }catch (Exception e){
            modelMap.put("error",-1);
            return modelMap;
        }
        SureKey sureKey = new SureKey();
        Date date = new Date();

        sureKey.setSendtime(simpleDateFormat.format(date));
        sureKey.setUname(uname);
        sureKey.setSurekey(key);
//        验证码发送成功
        keyService.addKey(sureKey);
        modelMap.put("error",1);
        modelMap.put("msg","验证码发送成功");
        return modelMap;

    }




    @ResponseBody
    @RequestMapping(value = "/update")
    public Map<String, Object> update(@RequestBody Map<String, Object> data) {
        modelMap.clear();
        User user = new User();
        String uname=(String )data.get("username");

        String pass = (String) data.get("password");
        user.setNickname((String) data.get("nickname"));
        user.setGender((Integer) data.get("gender"));
        user.setProfile((String) data.get("profile"));
        if (pass.equals(userService.queryPassword(uname))) {
            user.setPassword(pass);
        } else {
            user.setPassword(MD5Util.MD5(pass));
        }
        user.setUsername((String) data.get("username"));

        User flag = userService.updateUser(user);
        if (flag != null) {
            modelMap.put("errno", 0);
            modelMap.put("msg", "更新成功！");
        } else {
            modelMap.put("errno", -1);
            modelMap.put("msg", "更新失败！");
        }
        return modelMap;

    }

    @ResponseBody
    @RequestMapping(value="/newpass")
    public Map<String,Object> updatepassword(@RequestBody Map<String,Object> data){
        modelMap.clear();
        String username = (String) data.get("username");
        String password = (String) data.get("password");
        String np= MD5Util.MD5(password);
        userService.updatePass(np,username);
//        modelMap.put("error",1);
        modelMap.put("msg","1");
        return modelMap;
    }

    @ResponseBody
    @RequestMapping(value="/yes")
    public  Map<String ,Object> yeskey(@RequestBody Map<String ,Object>data) throws ParseException {
        modelMap.clear();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now =new Date();
        int flag =0;
        String uname= (String) data.get("username");
        String upass = (String) data.get("key");
//        String password = (String ) data.get("newpass");

        SureKey sureKey = new SureKey();
        sureKey = keyService.selectKey(uname);
//        返回是一个key实体

        if(sureKey.getSurekey().equals(upass)){


            String lastTime = sureKey.getSendtime();
            if (lastTime == null) {
                flag = 0;
            } else {
                Date last = simpleDateFormat.parse(lastTime);
                long now1 = now.getTime();
                long last1 = last.getTime();
                int days = (int) ((last1 - now1) / (1000 * 60 * 5));
//                b秒  c分钟
                if (days == 0) {
                    flag = 0;
                } else {
                    flag = 1;
                }
            }
            if (flag == 0) {
//                userService.checkin((String) data.get("username"), simpleDateFormat.format(now));
                modelMap.put("errno", 0);
                modelMap.put("msg", "验证成功");


            } else {
                modelMap.put("errno", -1);
                modelMap.put("msg", "验证时间过长，请重新输入！");
            }

        }else{
            modelMap.put("error",-1);
            modelMap.put("msg","密码错误！");
        }
        return modelMap;
    }


    @ResponseBody
    @RequestMapping(value = "/checkin")
    public Map<String, Object> checkin(@RequestBody Map<String, Object> data) throws ParseException {
        modelMap.clear();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        int flag = 0;
        String lastTime = userService.queryTime((String) data.get("username"));
        if (lastTime == null) {
            flag = 0;
        } else {
            Date last = simpleDateFormat.parse(lastTime);
            long now1 = now.getTime();
            long last1 = last.getTime();
            int days = (int) ((last1 - now1) / (1000 * 60 * 60 * 24));
            if (days != 0) {
                flag = 0;
            } else {
                flag = 1;
            }
        }
        if (flag == 0) {
            userService.checkin((String) data.get("username"), simpleDateFormat.format(now));
            modelMap.put("errno", 0);
            modelMap.put("msg", "签到成功！硬币+2");
        } else {
            modelMap.put("errno", -1);
            modelMap.put("msg", "您今天已签到过，请明天再来！");
        }
        return modelMap;

    }

    @ResponseBody
    @RequestMapping(value = "/seeinfo")
    public Map<String, Object> seeinfo(@RequestBody Map<String, Object> data) {
        modelMap.clear();
        String username = (String) data.get("username");
        Integer dataCount = dataService.listByName(username).size();
        Integer starCount = 0;
        List<Data> ldata = dataService.listByName(username);
        for (int i =0;i<ldata.size();i++){
            starCount= starCount+ldata.get(i).getStar();
        }
        userService.updateInfo(dataCount, starCount, username);
        User user = userService.queryByUsername(username);
        if (user != null) {
            modelMap.put("errno", 0);
            modelMap.put("result", user);
        } else {
            modelMap.put("errno", -1);
            modelMap.put("msg", "查看失败！");
        }
        return modelMap;
    }

    @ResponseBody
    @RequestMapping(value = "/updateSchoolAndMajor")
    public int updateSchoolAndMajor(String username, String school, String major) {
        return userService.updateSchoolAndMajor(username, school, major);
    }


    @ResponseBody
    @RequestMapping(value = "/down")
    public Map<String, Object> down(@RequestParam("id") Integer id,
                                    @RequestParam("username") String username) {
        modelMap.clear();
        Integer coin = userService.queryCoin(username);
        BigDecimal res = new BigDecimal(coin);
        Data data = dataService.getOne(id);
        System.out.println("data = " + data + ", res = " + res);
        int flag1=downFileService.alreadyDown(id,username);
        if(flag1!=0){
            modelMap.put("gg","您已经下载过了！本次下载不产生费用！");
            modelMap.put("msg", data.getImg());
        }else{
            if (res.compareTo(BigDecimal.valueOf(data.getPrice())) < 0) {
                modelMap.put("errno", -1);
                modelMap.put("msg", "硬币不足，无法购买！");
            } else {
                int flag = userService.decCoin(username, (int) (data.getPrice()));
                if (flag != 0) {
                    modelMap.put("errno", 0);
                    modelMap.put("msg", "硬币不足，购买失败！");
                } else {
                    modelMap.put("errno", 1);
                    modelMap.put("msg", data.getImg());
                    DownFile downFile = new DownFile();
                    downFile.setDataid(id);
                    downFile.setUsrname(username);
                    downFileService.addDown(downFile);
//                Counter counter=new Counter();
//                counter.setDataid(id);
                    counterService.addOne(id);

                }
            }
        }


        return modelMap;

    }


}
